{% extends 'base.html' %}

{% block title %}
购物车 - 数据管理系统
{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item"><a href="{{ url_for('list_main') }}">产品列表</a></li>
<li class="breadcrumb-item active" aria-current="page">购物车</li>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
  <h2 class="page-header">购物车</h2>
  <div>
    <button id="deleteSelectedBtn" class="btn btn-danger me-2" disabled><i class="bi bi-trash"></i> 删除选中</button>
    <a href="{{ url_for('list_main') }}" class="btn btn-outline-secondary me-2"><i class="bi bi-arrow-left"></i>
      返回产品列表</a>
    {% if cart_items %}
    <a href="{{ url_for('cart.generate_quotation') }}" class="btn btn-primary"><i class="bi bi-file-earmark-text"></i>
      生成报价单</a>
    {% endif %}
  </div>
</div>

{% if cart_items %}
<div class="table-responsive">
  <table class="table table-striped table-hover">
    <thead class="table-light">
      <tr>
        <th scope="col"><input type="checkbox" id="selectAllCart" class="form-check-input larger-checkbox" title="全选">
        </th>
        <th scope="col">产品</th>
        <th scope="col">图片</th>
        <th scope="col">规格</th>
        <th scope="col">价格范围</th>
        <th scope="col">库存</th>
        <th scope="col">操作</th>
      </tr>
    </thead>
    <tbody>
      {% for product_id, items in cart_items|groupby('product_id') %}
      {% if items|length > 0 %}
      {% set product = items[0].product %}
      {% set first_detail = items[0].product_detail %}
      {% set stat = product_stats|selectattr('product_id', 'equalto', product_id|string)|first %}
      <tr class="clickable-row" data-bs-toggle="collapse" data-bs-target="#details-{{ product_id }}"
        aria-expanded="false" aria-controls="details-{{ product_id }}" data-product-id="{{ product_id }}">
        <td>
          <input type="checkbox" class="cart-checkbox form-check-input larger-checkbox"
            data-product-id="{{ product_id }}" title="选择产品">
        </td>
        <td>
          <a href="{{ product.url }}" target="_blank" class="text-decoration-none">{{ product.title }}</a>
          <i class="bi bi-chevron-down ms-2"></i>
        </td>
        <td>
          {% if first_detail and (first_detail.local_image_path or first_detail.image_url) %}
          <a href="javascript:void(0);"
            onclick="showImageModal('{{ url_for('static', filename=first_detail.local_image_path) if first_detail.local_image_path else first_detail.image_url }}')">
            <img
              src="{{ url_for('static', filename=first_detail.local_image_path) if first_detail.local_image_path else first_detail.image_url }}"
              alt="产品图片" class="img-thumbnail" style="max-width: 100px;" />
          </a>
          {% else %}
          <span class="text-muted">无图片</span>
          {% endif %}
        </td>
        <td>
          {% if first_detail %}
          {{ first_detail.self_model or '默认规格' }}<br>
          <small class="text-muted d-block mt-1 spec-count" data-product-id="{{ product_id }}">{{ stat.spec_count
            }}种规格</small>
          {% else %}
          <span class="text-muted">无规格</span>
          {% endif %}
        </td>
        <td>
          {% if stat %}
          {% if stat.min_price == stat.max_price %}
          <span class="badge bg-success">¥{{ '%.2f'|format(stat.min_price) }}</span>
          {% else %}
          <div>
            <span class="badge bg-primary">¥{{ '%.2f'|format(stat.min_price) }}</span>
            至
            <span class="badge bg-primary">¥{{ '%.2f'|format(stat.max_price) }}</span>
          </div>
          {% endif %}
          {% else %}
          <span class="text-muted">无价格</span>
          {% endif %}
        </td>
        <td>
          {% if first_detail and first_detail.stock %}
          <span class="badge bg-secondary">{{ first_detail.stock }}</span>
          {% else %}
          <span class="text-muted">无库存</span>
          {% endif %}
        </td>
        <td>
          <button class="btn btn-sm btn-outline-danger delete-cart-item" data-cart-item-id="{{ items[0].id }}">
            <i class="bi bi-trash"></i> 删除
          </button>
        </td>
      </tr>
      {% if items|length > 1 %}
      <tr class="collapse" id="details-{{ product_id }}">
        <td colspan="8">
          <div class="p-3">
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>图片</th>
                  <th>自身型号</th>
                  <th>其他型号</th>
                  <th>单价</th>
                  <th>库存</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {% for item in items[1:] %}
                {% set detail = item.product_detail %}
                <tr data-cart-item-id="{{ item.id }}">
                  <td>
                    {% if detail and (detail.local_image_path or detail.image_url) %}
                    <a href="javascript:void(0);"
                      onclick="showImageModal('{{ url_for('static', filename=detail.local_image_path) if detail.local_image_path else detail.image_url }}')">
                      <img
                        src="{{ url_for('static', filename=detail.local_image_path) if detail.local_image_path else detail.image_url }}"
                        alt="规格图片" class="img-thumbnail" style="max-width: 80px;" />
                    </a>
                    {% else %}
                    <span class="text-muted">无图片</span>
                    {% endif %}
                  </td>
                  <td>{{ detail.self_model or '默认规格' }}</td>
                  <td>{{ detail.other_model or '无' }}</td>
                  <td>
                    {% if detail and detail.price %}
                    <span class="badge bg-success">¥{{ '%.2f'|format(detail.price) }}</span>
                    {% else %}
                    <span class="text-muted">未设置</span>
                    {% endif %}
                  </td>
                  <td>
                    {% if detail and detail.stock %}
                    <span class="badge bg-secondary">{{ detail.stock }}</span>
                    {% else %}
                    <span class="text-muted">无库存</span>
                    {% endif %}
                  </td>
                  <td>
                    <button class="btn btn-sm btn-outline-danger delete-cart-item" data-cart-item-id="{{ item.id }}">
                      <i class="bi bi-trash"></i> 删除
                    </button>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </td>
      </tr>
      {% endif %}
      {% endif %}
      {% endfor %}
    </tbody>
  </table>
</div>
{% else %}
<div class="alert alert-info" role="alert">
  购物车为空，请返回产品列表添加产品。
</div>
{% endif %}

<div id="cartStatus" class="text-muted small mt-3"></div>

<!-- 图片模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl">
    <div class="modal-content bg-transparent border-0">
      <div class="modal-body p-0 text-center">
        <img id="modalImage" src="" alt="放大图片" class="img-fluid" style="max-height: 80vh;" />
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block styles %}
<style>
  .larger-checkbox {
    transform: scale(1.5);
    margin: 0.5rem;
  }

  .clickable-row {
    cursor: pointer;
  }

  .clickable-row:hover {
    background-color: #f8f9fa;
  }

  .fade-out {
    animation: fadeOut 0.5s ease-out;
    animation-fill-mode: forwards;
  }

  @keyframes fadeOut {
    from {
      opacity: 1;
    }

    to {
      opacity: 0;
      height: 0;
      overflow: hidden;
    }
  }
</style>
{% endblock %}

{% block scripts %}
<script>
  // 通用工具函数
  function setCartStatus(message) {
    document.getElementById('cartStatus').textContent = message;
  }

  // 发起请求通用函数
  function fetchAPI(url, data) {
    console.log('[📡 fetchAPI] 发起请求:', { url, data });
    return fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
      .then(res => {
        console.log('[📡 fetchAPI] 响应状态:', res.status);
        return res.json().then(json => {
          if (!res.ok) throw new Error(json.message || '网络响应错误');
          return json;
        });
      });
  }

  // 处理错误
  function handleError(err, defaultMessage) {
    console.error('[❌ handleError]', err);
    setCartStatus(`${defaultMessage}：${err.message}`);
  }


  // 单个删除函数
  function deleteCartItem(cartItemId) {
    console.log('[🛒 deleteCartItem] 尝试删除单个购物车项:', cartItemId);
    if (!confirm('确定删除此规格吗？')) return;

    setCartStatus('正在删除...');
    fetchAPI('{{ url_for("cart.delete_cart_item") }}', { cart_item_id: cartItemId })
      .then(data => handleDeleteSuccess(cartItemId, data))
      .catch(err => handleError(err, '删除失败'));
  }

  function handleDeleteSuccess(cartItemId, data) {
    console.log('[✅ handleDeleteSuccess] 删除响应:', data);
    setCartStatus(data.message);
    if (!data.success) return;

    // 查找被删除的行（可能是主行或子行）
    const button = document.querySelector(`button[data-cart-item-id="${cartItemId}"]`);
    if (!button) {
      console.warn('[⚠️ handleDeleteSuccess] 找不到删除按钮:', cartItemId);
      setCartStatus('删除成功，但页面更新失败，请刷新');
      return;
    }

    const row = button.closest('tr');
    if (!row) {
      console.warn('[⚠️ handleDeleteSuccess] 找不到对应行:', cartItemId);
      setCartStatus('删除成功，但页面更新失败，请刷新');
      return;
    }

    // 获取产品ID（从行本身或父行获取）
    let productId = data.product_id || row.closest('[data-product-id]')?.dataset.productId;
    if (!productId) {
      console.warn('[⚠️ handleDeleteSuccess] 找不到产品ID:', cartItemId);
      return;
    }

    // 添加淡出效果
    row.classList.add('fade-out');

    setTimeout(() => {
      // 处理不同类型的行删除
      if (row.classList.contains('clickable-row')) {
        // 删除的是主行
        processMainRowDeletion(row, productId, data);
      } else {
        // 删除的是子行（规格）
        processSubRowDeletion(row, productId, data);
      }

      finalizeProductUpdate();
    }, 500);
  }

  // 处理主行删除
  function processMainRowDeletion(row, productId, data) {
    console.log('[🧹 processMainRowDeletion] 处理主行删除:', productId);
    const collapseRow = document.querySelector(`tr#details-${productId}`);

    // 移除整个产品（主行和折叠行）
    if (collapseRow) {
      collapseRow.classList.add('fade-out');
      setTimeout(() => collapseRow.remove(), 500);
    }
    row.remove();
  }


  // 处理子行（规格）删除
  function processSubRowDeletion(row, productId, data) {
    console.log('[🧹 processSubRowDeletion] 处理子行删除:', productId);
    // 移除当前行
    row.remove();

    // 更新产品统计信息
    const stat = data.product_stats?.find(stat => stat.product_id === productId);
    if (stat) {
      updateSpecCountAndPrice(productId, stat);
    }

    // 检查是否还有子行
    const collapseRow = document.querySelector(`tr#details-${productId}`);
    if (collapseRow) {
      const remainingSubRows = collapseRow.querySelectorAll('tbody tr');
      if (remainingSubRows.length === 0) {
        // 没有子行则移除折叠行
        collapseRow.remove();

        // 如果只剩下一个规格，提升为主行
        if (stat && stat.spec_count === 1) {
          promoteSubRowToMain(productId);
        }
      }
    }
  }

  // 批量删除函数
  function setupBulkDelete() {
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    deleteSelectedBtn.addEventListener('click', handleBulkDelete);
  }

  function handleBulkDelete() {
    console.log('[🗑️ handleBulkDelete] 尝试批量删除');
    if (!confirm('确定删除选中的产品吗？')) return;

    const productIds = getSelectedProductIds();
    console.log('[🗑️ handleBulkDelete] 选中的产品ID:', productIds);
    setCartStatus('正在删除...');
    fetchAPI('{{ url_for("cart.delete_selected_cart_items") }}', { product_ids: productIds })
      .then(data => handleBulkDeleteSuccess(data))
      .catch(err => handleError(err, '批量删除失败'));
  }

  function getSelectedProductIds() {
    return Array.from(document.querySelectorAll('.cart-checkbox'))
      .filter(cb => cb.checked)
      .map(cb => cb.dataset.productId);
  }


  function handleBulkDeleteSuccess(data) {
    console.log('[✅ handleBulkDeleteSuccess] 批量删除响应:', data);
    setCartStatus(data.message);
    if (!data.success) return;

    // 移除所有被删除的产品行
    data.removed_products.forEach(productId => {
      console.log('[🗑️ handleBulkDeleteSuccess] 移除产品:', productId);
      removeEntireProduct(productId);
    });

    // 更新剩余产品的统计信息
    data.product_stats.forEach(stat => {
      if (stat.spec_count > 0) {
        console.log('[🔄 handleBulkDeleteSuccess] 更新产品统计:', stat);
        updateSpecCountAndPrice(stat.product_id, stat);
      }
    });

    finalizeProductUpdate();
  }

  // DOM 操作函数
  function processItemUpdate(cartItemId, data, row = null) {
    console.log('[🧹 processItemUpdate] 处理项目更新:', { cartItemId, data });
    const productId = data.product_id || data.removed_products[0] || (row?.closest('[data-product-id]')?.dataset.productId);

    if (data.removed_products?.includes(productId) || (data.product_stats?.find(stat => stat.product_id === productId)?.spec_count === 0)) {
      console.log('[🧨 processItemUpdate] 产品被完全移除:', productId);
      removeEntireProduct(productId);
    } else if (row) {
      console.log('[🔪 processItemUpdate] 删除单行:', cartItemId);
      row.remove();
      const stat = data.product_stats?.find(stat => stat.product_id === productId);
      if (stat) {
        updateSpecCountAndPrice(productId, stat);
      }
      if (row.classList.contains('clickable-row')) {
        promoteSubRowToMain(productId);
      }
    }
  }

  function removeEntireProduct(productId) {
    const mainRow = document.querySelector(`tr[data-product-id="${productId}"]`);
    const collapseRow = document.querySelector(`tr#details-${productId}`);
    console.log('[🗑️ removeEntireProduct] 移除整个产品:', { mainRow: !!mainRow, collapseRow: !!collapseRow });
    if (mainRow) {
      mainRow.classList.add('fade-out');
      setTimeout(() => mainRow.remove(), 500);
    }
    if (collapseRow) {
      collapseRow.classList.add('fade-out');
      setTimeout(() => collapseRow.remove(), 500);
    }
  }


  // 更新规格数量和价格显示
  function updateSpecCountAndPrice(productId, stat) {
    const specCountEl = document.querySelector(`.spec-count[data-product-id="${productId}"]`);
    if (!specCountEl) return;

    specCountEl.textContent = `${stat.spec_count}种规格`;
    const priceCell = specCountEl.closest('tr').querySelector('td:nth-child(5)');
    if (priceCell) {
      priceCell.innerHTML = stat.min_price === stat.max_price
        ? `<span class="badge bg-success">¥${stat.min_price.toFixed(2)}</span>`
        : `
                <div>
                    <span class="badge bg-primary">¥${stat.min_price.toFixed(2)}</span>
                    至
                    <span class="badge bg-primary">¥${stat.max_price.toFixed(2)}</span>
                </div>`;
    }
  }

  function promoteSubRowToMain(productId) {
    const collapseRow = document.querySelector(`tr#details-${productId}`);
    if (!collapseRow) return;

    console.log('[🔄 promoteSubRowToMain] 提升子行为主行:', productId);
    const firstSubRow = collapseRow.querySelector('tbody tr');
    if (!firstSubRow) {
      collapseRow.remove();
      return;
    }

    const newMainRow = createMainRow(productId, collapseRow, firstSubRow);
    collapseRow.before(newMainRow);
    firstSubRow.remove();

    if (!collapseRow.querySelector('tbody tr')) {
      console.log('[🗑️ promoteSubRowToMain] 没有剩余子行，移除折叠行:', productId);
      collapseRow.remove();
    }
  }

  function createMainRow(productId, collapseRow, firstSubRow) {
    const newMainRow = document.createElement('tr');
    newMainRow.className = 'clickable-row';
    newMainRow.setAttribute('data-product-id', productId);
    newMainRow.setAttribute('data-bs-toggle', 'collapse');
    newMainRow.setAttribute('data-bs-target', `#details-${productId}`);
    newMainRow.setAttribute('aria-expanded', collapseRow.classList.contains('show') ? 'true' : 'false');
    newMainRow.setAttribute('aria-controls', `details-${productId}`);

    const product = firstSubRow.querySelector('td:nth-child(2)')?.textContent || '未知产品';
    const imageCell = firstSubRow.querySelector('td:first-child')?.innerHTML || '<span class="text-muted">无图片</span>';
    const specCountEl = document.querySelector(`.spec-count[data-product-id="${productId}"]`);
    const priceCell = specCountEl?.closest('tr')?.querySelector('td:nth-child(5)')?.innerHTML || '';
    const stock = firstSubRow.querySelector('td:nth-child(5)')?.innerHTML || '<span class="text-muted">无库存</span>';

    newMainRow.innerHTML = `
        <td><input type="checkbox" class="cart-checkbox form-check-input larger-checkbox" data-product-id="${productId}" title="选择产品"></td>
        <td><a href="#" class="text-decoration-none">${product}</a> <i class="bi bi-chevron-down ms-2"></i></td>
        ${imageCell}
        <td><small class="text-muted d-block mt-1 spec-count" data-product-id="${productId}"></small></td>
        ${priceCell}
        ${stock}
        <td><button class="btn btn-sm btn-outline-danger delete-cart-item" data-cart-item-id="${firstSubRow.dataset.cartItemId}"><i class="bi bi-trash"></i> 删除</button></td>
    `;

    const deleteBtn = newMainRow.querySelector('.delete-cart-item');
    deleteBtn.addEventListener('click', () => deleteCartItem(firstSubRow.dataset.cartItemId));

    return newMainRow;
  }

  function finalizeProductUpdate() {
    updateDeleteButtonState();
    const remainingRows = document.querySelectorAll('tbody tr:not(.collapse)').length;
    console.log('[🔍 finalizeProductUpdate] 剩余行数:', remainingRows);
    if (remainingRows === 0) {
      replaceTableWithEmptyState();
    }
  }

  function replaceTableWithEmptyState() {
    document.querySelector('.table-responsive').outerHTML = `
        <div class="alert alert-info" role="alert">
            购物车为空，请返回产品列表添加产品。
        </div>`;
  }

  // 图片模态框函数
  function showImageModal(imageUrl) {
    console.log('[🖼️ showImageModal] 显示图片:', imageUrl);
    document.getElementById('modalImage').src = imageUrl;
    new bootstrap.Modal(document.getElementById('imageModal')).show();
  }

  // 选择框和删除按钮状态
  function updateDeleteButtonState() {
    const cartCheckboxes = document.querySelectorAll('.cart-checkbox');
    const selectedIds = Array.from(cartCheckboxes).filter(cb => cb.checked);
    console.log('[✅ updateDeleteButtonState] 选中的产品ID:', selectedIds.map(cb => cb.dataset.productId));
    document.getElementById('deleteSelectedBtn').disabled = selectedIds.length === 0;
  }

  // 页面初始化
  function initializeCartPage() {
    console.log('[📄 initializeCartPage] 页面加载完成');
    initializeTooltips();
    setupImageModalEvents();
    setupSelectAllCheckbox();
    setupCartCheckboxes();
    setupDeleteItemButtons();
    setupBulkDelete();
  }

  function initializeTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
  }

  function setupImageModalEvents() {
    const imageModal = document.getElementById('imageModal');
    imageModal.addEventListener('click', e => {
      if (e.target === imageModal) {
        bootstrap.Modal.getInstance(imageModal).hide();
      }
    });
    document.getElementById('modalImage').addEventListener('click', e => e.stopPropagation());
  }

  function setupSelectAllCheckbox() {
    const selectAllCart = document.getElementById('selectAllCart');
    selectAllCart.addEventListener('change', e => {
      console.log('[✅ setupSelectAllCheckbox] 全选状态改变:', e.target.checked);
      document.querySelectorAll('.cart-checkbox').forEach(cb => {
        cb.checked = e.target.checked;
      });
      updateDeleteButtonState();
    });
  }

  function setupCartCheckboxes() {
    const cartCheckboxes = document.querySelectorAll('.cart-checkbox');
    const selectAllCart = document.getElementById('selectAllCart');
    cartCheckboxes.forEach(cb => {
      cb.addEventListener('change', () => {
        console.log('[✅ setupCartCheckboxes] 复选框改变:', cb.dataset.productId, cb.checked);
        selectAllCart.checked = Array.from(cartCheckboxes).every(checkbox => checkbox.checked);
        updateDeleteButtonState();
      });
    });
  }

  function setupDeleteItemButtons() {
    document.querySelectorAll('.delete-cart-item').forEach(button => {
      button.addEventListener('click', () => {
        const cartItemId = button.dataset.cartItemId;
        console.log('[🗑️ setupDeleteItemButtons] 删除按钮点击:', cartItemId);
        deleteCartItem(cartItemId);
      });
    });
  }

  document.addEventListener('DOMContentLoaded', initializeCartPage);
</script>
{% endblock %}